import React, {useRef} from "react";
import {Card} from "antd";
import {connect, Dispatch} from "dva";
import {AnyAction} from "redux";
import styles from "./index.less";
import ProTable, {ActionType, ProColumns, RequestData} from "@ant-design/pro-table";
import {transformParams} from "@/utils/utils";
import organizationService from "@/services/organization";
import GridContainer from "@/components/GridContainer";
import {ProfileVO} from "@/types/common";
import _ from 'lodash';
import {TabCardPermission} from "@/components/Permission";
import DepartmentList from "../department/List";
import {DepartmentCreateForm} from "../department/Form";
import RoleList from "../role/List";
import {RoleCreateForm,} from "../role/Form";
import UserList from "../user/List";
import {UserCreateForm} from "@/pages/integrate/user/Form";

interface Props {
  dispatch: Dispatch<AnyAction>;
}

interface State{
  selectedKeys:(string|number)[];
}

class List extends React.Component<Props, State> {

  actionRef:ActionType | undefined;

  state={
    selectedKeys:[],
  }

  onSelect=(selectedKeys: (string|number)[])=>{
    this.setState({selectedKeys});
  }

  onReset=()=>{
    const reset=this.actionRef?.reset;
    reset&&reset();
  }

  render() {

    const {
      selectedKeys
    }=this.state;

    const params=selectedKeys.length>0?{
      organizationId:selectedKeys[0]
    }:undefined

    const functionObject={
      'menu.integrate.department': {
        extra:()=><DepartmentCreateForm entity={params} onReset={this.onReset} />,
        component:()=><DepartmentList params={params}  actionRef={(actionRef)=>this.actionRef=actionRef} />
      },
      'menu.integrate.role':{
        extra:()=><RoleCreateForm entity={params} onReset={this.onReset} />,
        component:()=><RoleList params={params}  actionRef={(actionRef)=>this.actionRef=actionRef} />
      },
      'menu.integrate.user':{
        extra:()=><UserCreateForm entity={params} onReset={this.onReset} />,
        component:()=><UserList params={params}  actionRef={(actionRef)=>this.actionRef=actionRef} />
      }
    }

    return (
      <GridContainer>
        <Card
          bordered={false}
          title={'单位列表'}
          className={styles.left}
        >
          <OrganizationList selectedKeys={selectedKeys} onSelect={this.onSelect}/>
        </Card>
        {selectedKeys.length>0&&(
          <TabCardPermission
            className={styles.right}
            size={'small'}
            functionObject={functionObject}
            tabProps={{
              type:'card'
            }}
          />
        )}
      </GridContainer>
    );
  }
}


interface OrganizationListProps {
  selectedKeys:(string|number)[];
  onSelect:(selectedKeys:(string|number)[])=>void
}

const OrganizationList: React.FC<OrganizationListProps> = (props:OrganizationListProps) => {

  const actionRef = useRef<ActionType>();

  const onRow = (data:any):React.HTMLAttributes<HTMLElement> => {
    return {
      onClick: () => {
        if(!props.selectedKeys?.includes(data.organization.id)){
          props.onSelect([data.organization.id]);
        }
      },
    };
  }

  const rowClassName = (data:any) => {
    return props.selectedKeys?.includes(data.organization.id) ? styles['selected-row'] : undefined;
  }

  const queryList= async (params:any, sorter:any, filter:any): Promise<RequestData<ProfileVO>> => {
    let paramsObject={
      ...params,
      ...params.organization,
    }
    delete paramsObject.organization;
    let sortObject={};
    _.forIn(sorter,(value,key)=>{
      const sortKey=key.split(',')[1];
      sortObject[sortKey]=value;
    })
    const  dto = transformParams(paramsObject, sortObject);
    const response=await organizationService.queryList(dto);
    const {data}=response;
    const {pagination}=data;
    if(data && data.items && data.items.length>0){
      props.onSelect([data.items[0].organization.id]);
    }
    return {
      success:true,
      data:data.items,
      total:pagination.total,
    };
  }

  const columns: ProColumns<ProfileVO>[] = [
    {
      title: '公司名称',
      align:'left',
      dataIndex: ['organization','name'],
    },
  ];

  return (
    <ProTable<ProfileVO>
      actionRef={actionRef}
      // @ts-ignore
      rowKey={((record) => record.organization?.id)}
      showHeader={false}
      search={false}
      size={'small'}
      pagination={{
        pageSize:10,
        showTotal:(total => null),
        showSizeChanger:false,
      }}
      className={styles.table}
      onRow={onRow}
      rowClassName={rowClassName}
      toolBarRender={false}
      request={queryList}
      columns={columns}
    />
  );
};


export default connect()(List)
